package cn.iocoder.yudao.module.promotion.redpacket.service.admin;

import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.service.PageService;
import cn.iocoder.yudao.framework.business.basic.service.impl.BaseService;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.api.promotion.redpacket.vo.RedPacketConfigVO;
import cn.iocoder.yudao.module.promotion.redpacket.convert.RedPacketConfigConvert;
import cn.iocoder.yudao.module.promotion.redpacket.dao.RedPacketConfigMapper;
import cn.iocoder.yudao.module.promotion.redpacket.pojo.dto.RedPacketConfigQueryDTO;
import cn.iocoder.yudao.module.promotion.redpacket.pojo.dto.RedPacketConfigSaveDTO;
import cn.iocoder.yudao.module.promotion.redpacket.pojo.po.RedPacketConfig;
import cn.iocoder.yudao.module.promotion.redpacket.service.core.CoreRedPacketConfigService;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 服务
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/06/21
 */
@Service
public class RedPacketConfigService extends BaseService<RedPacketConfig, RedPacketConfigVO, RedPacketConfigQueryDTO> implements PageService<RedPacketConfigVO, RedPacketConfigQueryDTO> {
    @Resource
    private RedPacketConfigMapper redPacketConfigMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private CoreRedPacketConfigService coreRedPacketConfigService;

    @Override
    public RedPacketConfigMapper getInjectedMapper() {
        return redPacketConfigMapper;
    }

    @Nonnull
    @Override
    protected CoreQueryWrapper<RedPacketConfig> buildQueryWrapper(RedPacketConfigQueryDTO param) {
        CoreQueryWrapper<RedPacketConfig> wrapper = super.buildQueryWrapper(param);
        wrapper.eqIfPresent("shop_id", param.getShopId());
        return wrapper;
    }

    @Override
    public RedPacketConfigVO convertToViewObject(RedPacketConfig entity) {
        return RedPacketConfigConvert.INSTANCE.toViewObject(entity);
    }

    @DataPermission(enable = false)
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(Long shopId, RedPacketConfigSaveDTO param) {
        RedPacketConfig entity = RedPacketConfigConvert.INSTANCE.toEntity(param);
        entity.setShopId(shopId);
        RedPacketConfig config = coreRedPacketConfigService.getOrCreate(shopId);
        entity.setId(config.getId());
        return redPacketConfigMapper.updateById(entity) > 0;
    }

}
